package summer.codegenerator.persistence.hibernate.base.tool;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author jiangz
 * @birth  2017年12月4日 下午10:46:59
 */
public class ConditionGroupGroup implements Serializable,WhereClause {

	private static final long serialVersionUID = 1L;

	private List<ConditionGroup> groups;

	private String logic;

	public ConditionGroupGroup() {
		this.groups = new ArrayList<ConditionGroup>();
		this.logic = "or";
	}

	public ConditionGroupGroup(List<ConditionGroup> groups, String groupLogic) {
		this.groups = groups;
		this.logic = groupLogic;
	}

	@Override
	public String getClause() {

		// 清除无用条件组
		Iterator<ConditionGroup> iterator = groups.iterator();
		while (iterator.hasNext()) {
			ConditionGroup group = iterator.next();
			if (group.useless()) {
				iterator.remove();
			}
		}

		int groupCount = groups.size();
		if (groups == null || groupCount == 0) {
			return "";
		}

		StringBuilder clause = new StringBuilder(" where ");
		if (groupCount == 1) {
			ConditionGroup group = groups.get(0);
			clause.append(group.toString());
		} else {
			for (int i = 0; i < groupCount - 1; i++) {
				ConditionGroup group = groups.get(i);
				clause.append(String.format("%s %s ", group.toString(), this.logic));
			}
			clause.append(groups.get(groupCount - 1));
		}
		return clause.toString();
	}
	
	@Override
	public Map<String, Object> getParamMap() {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		for(ConditionGroup group : this.groups) {
			paramMap.putAll(group.getParamMap());
		}
		return paramMap;
	}

	public List<ConditionGroup> getGroups() {
		return groups;
	}

	public void setGroups(List<ConditionGroup> groups) {
		this.groups = groups;
	}

	public String getLogic() {
		return logic;
	}

	public void setLogic(String logic) {
		this.logic = logic;
	}

}
